package com.zx.mes.rocketmq.hyl.quickstart;

import com.zx.mes.rocketmq.hyl.constant.Const;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * quick start rocketMq consumer
 * @author 华云龙
 * @date 2018-11-27
 */
public class Consumer {

    public static final String CONSUMER_GROUP = "test_quick_consumer_name";
    public static final String TEST_QUICK_TOPIC = "test_quick_topic";

    public static void receive() throws MQClientException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
        consumer.setConsumerGroup(CONSUMER_GROUP);
        consumer.setNamesrvAddr(Const.NAMESRV_ADDR_SINGLE);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        /// MQClientException
        /// 订阅主题来消费
        consumer.subscribe(TEST_QUICK_TOPIC,"*");
        /// Register callback to execute on arrival of messages fetched from brokers
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            MessageExt messageExt = msgs.get(0);

            /// try catch 固定写法
            try {
                String topic = messageExt.getTopic();
                String msgId = messageExt.getMsgId();
                String keys = messageExt.getKeys();
                String body = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                System.out.println(sdf.format(new Date())+"topic:"+topic+" msgid:"+msgId+" keys:"+keys+" body:"+body);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        /// 开始消费
        consumer.start();
        System.out.print("Consumer Started");

    }

    public static void main(String []args) throws MQClientException, InterruptedException {
        Consumer.receive();
    }
}
